package com.java.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author jl
 * Created on 2020/9/27
 */
public class NIOFileChannel03 {

    public static void main(String[] args) throws Exception{
        FileInputStream fileInputStream = new FileInputStream("1.txt");
        FileChannel fileChannel1 = fileInputStream.getChannel();

        FileOutputStream fileOutputStream = new FileOutputStream("2.txt");
        FileChannel fileChannel2 = fileOutputStream.getChannel();

        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        while (true) {
            // 清空byteBuffer,重置标志位
            byteBuffer.clear();
            // 将channel中的数据读入到buffer
            int read = fileChannel1.read(byteBuffer);
            if (read == -1) {
                break;
            }
            // 读写切换
            byteBuffer.flip();
            // 将byteBuffer中的数据写入channel
            fileChannel2.write(byteBuffer);
        }

        fileInputStream.close();
        fileOutputStream.close();
    }
}
